package com.smm.web.mtower.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

/**
 * Created by zhenghao on 2016/6/24.
 * 当前位置处理工具
 */
public class LocationUtil {

    /**
     * 获取指定IP对应的经纬度（为空返回当前机器经纬度）
     * @return
     */
    public static Location getIPXY() {

        //获取本机公网ip
        String ip = getPublicWebIP();

        if(ip==null || ip.trim().equals("")) return null;

        //百度map ak
        String ak = "TjoQTe9hGpLQjVydv1zOPlaio3ZBj8jV";

        try {

            //读取指定url地址的返回内容
            String str = UrlUtil.getContent("http://api.map.baidu.com/location/ip?ak=" + ak + "&ip=" + ip + "&coor=bd09ll");

            if(str==null) return null;

            //去掉返回结果中的 null 字符
            str = str.replace("null","");

            //json 格式转换
            JSONObject  obj = JSON.parseObject(str);

            JSONObject content= (JSONObject) obj.get("content");

            JSONObject point= (JSONObject) content.get("point");

            // 获取坐标位置
            return new Location(point.getString("y"),point.getString("x"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 获取本机公网ip
     * @return
     */
    public static String getPublicWebIP() {

        String http_url ="http://www.ip.cn/";

        try{

            String str = UrlUtil.getContent(http_url);

            if(str==null) return null;

            //从内容中截取代码 <code>117.184.120.234</code>

            int start = str.indexOf("code") + "code>".length();

            int end = str.lastIndexOf("code")-2;

            str = str.substring(start,end);

            return str;


        }catch (Exception e){

            e.printStackTrace();
        }

        return null;
    }


    public static void main(String[] args) {

        Location location = LocationUtil.getIPXY();

        assert location != null;

        System.out.println("widu:"+location.getWidu());

        System.out.println("jndu:"+location.getJndu());

    }

}
